package com.kotlin.dongdong.framework.ormlite

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.util.Log

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper
import com.j256.ormlite.support.ConnectionSource
import com.j256.ormlite.table.TableUtils

import java.util.ArrayList

/**
 * Created by dongdong on 2018/1/31.
 */

class DBHelper private constructor() : OrmLiteSqliteOpenHelper(dbcontext, DB_NAME, null, DB_VERSION) {


    @Suppress("UNREACHABLE_CODE")
    override fun onCreate(database: SQLiteDatabase?, connectionSource: ConnectionSource?) {
        // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        try {
            Log.d(TAG, "开始创建表。。。。。。。")
            for (cly: Class<*> in dbTables) {
                TableUtils.createTableIfNotExists(connectionSource, cly)
            }
        } catch (e: Exception) {
            Log.d(TAG, "创建表错误：" + e.toString())
        }

    }

    override fun onUpgrade(database: SQLiteDatabase?, connectionSource: ConnectionSource?, oldVersion: Int, newVersion: Int) {
        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        Log.d(TAG, "判断表版本信息--------oldVersion：" + oldVersion + "---newVersion:" + newVersion)
        if (newVersion > 1) {
            for (cly: Class<*> in dbTables) {
                DataBaseUpTools.upGradeTable(database!!, DB_NAME, cly)
            }

            onCreate(database, connectionSource)
        }
    }


    override fun close() {
        if (!isInit) {
            return
        }
        super.close()
        instance = null
    }


    companion object {

        private var TAG: String = "DBHelper"
        /**
         * 数据库名字
         */
        private var DB_NAME = "test.db"
        private var dbcontext: Context? = null

        /**
         * 数据库版本
         */
        private var DB_VERSION = 1

        private val dbTables = ArrayList<Class<*>>()

        var isInit = false
            private set

        private var instance: DBHelper? = null

        public fun initDB(context: Context, dbName: String, dbVersion: Int, tables: List<Class<*>>?) {

            dbcontext = context
            DB_NAME = dbName
            DB_VERSION = dbVersion
            dbTables.clear()
            if (null != tables) {
                dbTables.addAll(tables)
            }
            isInit = true
        }

        /**
         * 获取单例
         *
         * @return
         */
        public val helper: DBHelper?
            @Synchronized get() {
                if (instance == null) {
                    synchronized(DBHelper::class.java) {
                        if (instance == null) {
                            assert(isInit)
                            instance = DBHelper()
                        }
                    }
                }

                return this!!.instance
            }
    }
}

